package abstergo.tbs.betterasyc.Handler;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import androidx.annotation.NonNull;

import java.util.HashMap;

public final class HandlerMananger implements Handler.Callback {
    HashMap<Integer,IHandlerAction> actionHashMap=new HashMap<>();
    Handler handler=new Handler(Looper.getMainLooper(),this);
    private static HandlerMananger mananger;
    private HandlerMananger()
    {

    }
    public static Message MakeMsg(int code)
    {
        Message msg=new Message();
        msg.what=code;
        return msg;
    }
    public HandlerMananger SendMsg(Message msg,long delay)
    {
        mananger.handler.sendMessageDelayed(msg,delay);
        return this;
    }
    public HandlerMananger SendMsg(Message msg)
    {
        mananger.handler.sendMessage(msg);
        return this;
    }
    public static HandlerMananger Subscribe(int code,IHandlerAction action,boolean override)
    {
        boolean ishad= Instance().actionHashMap.containsKey(code);
        if(!ishad||override&&ishad)
        {
            Instance().actionHashMap.put(code,action);
            return Instance();
        }
        else
            throw new RuntimeException("不支持已存在且不覆盖的订阅操作");
    }
    public HandlerMananger Subscribe(int code,IHandlerAction action)
    {
        Subscribe(code,action,true);
        return this;
    }
    public boolean HasSubscribe(int code)
    {
        return actionHashMap.containsKey(code);
    }
    public static HandlerMananger Instance()
    {
        if(mananger==null)
            mananger=new HandlerMananger();
        return mananger;
    }

    @Override
    public boolean handleMessage(@NonNull Message msg) {
        if(actionHashMap.containsKey(msg.what))
        {
            actionHashMap.get(msg.what).Handle(msg);
        }
        else
            throw  new RuntimeException("无效方法代号:"+msg.what);
        return false;
    }
}
